package com.yry.timertask.chapter33;

import org.junit.jupiter.api.Test;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;

public class MyTimerDifference2Test {

	@Test
	public void scheduleTest(){
         //1.规定时间格式
		 Calendar calendar = Calendar.getInstance();
		 SimpleDateFormat sf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		 System.out.println("Current exec time is:"+sf.format(calendar.getTime()));


		 Timer timer = new Timer();
		 timer.schedule(new TimerTask() {
			 @Override
			 public void run() {
				 SimpleDateFormat sf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				 try {
					 Thread.sleep(3000L);
				 } catch (InterruptedException e) {
					 e.printStackTrace();
				 }
				 System.out.println("Scheduled exec time is:"+sf.format(scheduledExecutionTime())+", Task is being executed!");
			 }
		 }, calendar.getTime(), 2000);
		//休眠5s
		try {
			Thread.sleep(10000L);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	 }

	@Test
	public void scheduleAtFixRateTest(){
		//1.规定时间格式
		Calendar calendar = Calendar.getInstance();
		SimpleDateFormat sf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		System.out.println("Current exec time is:"+sf.format(calendar.getTime()));


		Timer timer = new Timer();
//		 timer.schedule(new TimerTask() {
		timer.scheduleAtFixedRate(new TimerTask() {
			@Override
			public void run() {
				SimpleDateFormat sf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				try {
					Thread.sleep(3000L);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				System.out.println("Scheduled exec time is:"+sf.format(scheduledExecutionTime()) + ", Task is being executed!");
			}
		}, calendar.getTime(), 2000);
		//休眠5s
		try {
			Thread.sleep(100000L);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
